package com.example.android.debuggermenu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;

import com.example.android.debuggermenu.Friends.FriendRowAdapter;

import clientcore.GameState;
import clientcore.Message;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MessageList extends ListActivity {
	private Vector<Message> messageList = new Vector<Message>();
	private Context mContext = this;
	private String buddyName = null, buddyMessage = null;
	private String[] friends;
	private AlertDialog inviteAlert;
	private ArrayAdapter<Message> myAdapter;
	private AlertDialog.Builder builder;
	private AlertDialog respondDialog;
	private boolean responded = false;
	private int numOfChats=0, numOfInvites=0;
	private HashMap<String, Boolean> buds = new HashMap<String, Boolean>();
	private int listItemPosition = 0;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("InviteList", "get the list");
		messageList = GameState.getMessageList();
		Collections.reverse(messageList);
		new loadData().execute();
		Log.d("MessageList", "size: " + messageList.size());
		
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		respondDialog(position, parent);
	}
	
	public void respondDialog(int position, ListView parent) {
		listItemPosition = position;
		Message item = (Message) parent.getItemAtPosition(position);
		buddyName = item.getSender();
		buddyMessage = item.getText();
		
		View respondDialogBox = this.getLayoutInflater().inflate(R.layout.respond_dialog, (ViewGroup)findViewById(R.id.respond_dialog));
		builder = new AlertDialog.Builder(this);
		builder.setView(respondDialogBox);
		
		final Button respondSend = (Button) respondDialogBox.findViewById(R.id.respond_sendButton);
		final Button respondCancel = (Button) respondDialogBox.findViewById(R.id.respond_cancelButton);
		final TextView scrollText = (TextView) respondDialogBox.findViewById(R.id.respond_scroll);
		final ScrollView sv = (ScrollView) respondDialogBox.findViewById(R.id.respond_scrollview);
		final EditText response = (EditText) respondDialogBox.findViewById(R.id.respond_edit_txt);
		
		scrollText.setText(buddyMessage);
		
		respondSend.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				buddyMessage = response.getText().toString();
				long status = GameState.sendPrivateChat(buddyName, buddyMessage);
				if (status == -1) {
					respondDialog.dismiss();
					Toast.makeText(mContext, "Invalid username", Toast.LENGTH_SHORT).show();
				} else if (status == 0) {
					respondDialog.dismiss();
					Toast.makeText(mContext, buddyName + " is offline", Toast.LENGTH_SHORT).show();
				} else if (status == 1) {
					respondDialog.dismiss();
					Toast.makeText(mContext, "Message sent to:\n" + buddyName, Toast.LENGTH_SHORT).show();
					responded = true;
					GameState.removeMessage(listItemPosition);
					messageList = GameState.getMessageList();
					myAdapter.notifyDataSetChanged();
				}
			}
		});
		
		respondCancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				respondDialog.dismiss();
			}
		});
		
		respondDialog = builder.create();
		respondDialog.show();
	}
	
	
	
class MessageListAdapter extends ArrayAdapter<Message> {
	private Vector<Message> messages;
    	
	public MessageListAdapter(Context context, int textViewResourceId, Vector<Message> items) {
    	super(context, textViewResourceId, items);
    	this.messages = items;
    }
    	
    public View getView(int position, View convertView, ViewGroup parent) {
    	View v = convertView;
    	if (v == null) {
    		LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		v = vi.inflate(R.layout.messagelist_row, null);
    	}
    	Message chat = messages.get(position);
    	TextView name = (TextView) v.findViewById(R.id.message_username);
    	TextView text = (TextView) v.findViewById(R.id.message);
    	name.setText(chat.getSender());
    	text.setText(chat.getText());
    	return v;
    }
}

private class loadData extends AsyncTask<Void, Void, HashMap<String, Boolean>> {
	private ProgressDialog dialog;

	protected void onPreExecute() {
		Log.d("LoadBuddies", "begin onPreExecute");
		dialog = new ProgressDialog(mContext);
		dialog.setMessage("Loading Buddy List...");
		dialog.setCancelable(false); 
		dialog.show();
	}
	
	@Override
	protected HashMap<String, Boolean> doInBackground(Void... arg0) {
		Log.d("LoadBuddies", "begin doInBackground");
		
		Vector<Message> chatMessages = GameState.updatePrivateChats();
		Log.d("getChats", "connection made");
		for(Message m : chatMessages) {
	      	Log.d("CHATS", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
	      	GameState.addMessage(m);
	    }
		numOfChats = chatMessages.size();
		chatMessages.clear();
		
		Vector<Message> inviteMessages = GameState.updateBuddyInvites();
		Log.d("LoadBuddies", "connection made for invites");
		for(Message m : inviteMessages) {
        	Log.d("BUDDY INVITES", "SENDER: " + m.getSender() + " MESSAGE: " + m.getText());
        	GameState.addInvite(m);
        }
		numOfInvites = inviteMessages.size();
		inviteMessages.clear();
		
       buds = GameState.getBuddies();
        if(buds != null) {
		    for(String name : buds.keySet()) {
		    	Log.d("Friends", name + " " + (buds.get(name)? "online" : "offline"));
		    }
        }
		return buds;
	}
	
	protected void onPostExecute(HashMap<String, Boolean> result) {
		Log.d("LoadBuddies", "begin onPostExecute");
		if (numOfChats > 0) {
			Toast.makeText(mContext, numOfChats + " new messages!", Toast.LENGTH_LONG).show();
		}
		if (numOfInvites > 0) {
			Toast.makeText(mContext, numOfInvites + " new invites!", Toast.LENGTH_LONG).show();
		}
		
		setContentView(R.layout.messagelist_layout);
		myAdapter = new MessageListAdapter(mContext, R.layout.messagelist_row, messageList);
		setListAdapter(myAdapter);
		dialog.dismiss();
	}
}

}

